<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>引出生命周期</title>
  <!-- 引入React核心库 -->
  <script type="text/javascript" src="../js/react.development.js"></script>
  <!-- 引入react-dom,用于支持react操作DOM -->
  <script type="text/javascript" src="../js/react-dom.development.js"></script>
  <!-- 引入babel，用于把jsx转为js -->
  <script type="text/javascript" src="../js/babel.min.js"></script>
  <!-- 引入prop-types,用于对prop进行限制 -->
  <script type="text/javascript" src="../js/prop-types.js"></script>
</head>

<body>
  <div id="test"></div>
</body>
<script type="text/babel">
  // 创建组件
  class Life extends React.Component {
    state = {
      opacity: 1
    }
    death = () => {
      ReactDOM.unmountComponentAtNode(document.getElementById('test'))
    }

    // 组件挂载完毕
    componentDidMount () {
      this.timer = setInterval(() => {
        let { opacity } = this.state
        opacity -= 0.1
        if (opacity <= 0) {
          opacity = 1
        }
        this.setState({ opacity })
      }, 200)
    }

    // 组件卸载前调用
    componentWillUnmount () {
      clearInterval(this.timer)
    }

    // 初始化渲染、页面更新之后
    render () {
      return (
        <div>
          <h1 style={{ opacity: this.state.opacity }}>React学不会怎么办</h1>
          <button onClick={this.death}>不活了</button>
        </div>
      )
    }
  }

  // 渲染组件
  ReactDOM.render(<Life />, document.getElementById('test'))
</script>

</html>